#define _CRT_SECURE_NO_WARNINGS 1

#include"string.h"
#include<string>

class Solution {
public:

    void reverse(string& str, int begin, int end)
    {
        char ch;
        while (begin < end)
        {
            ch = str[begin];
            str[begin] = str[end];
            str[end] = ch;
            ++begin, --end;
        }
    }

    string reverseWords(string s)
    {
        int begin = 0, end = s.find(' ', begin) - 1;
        while (end > -1)
        {
            reverse(s, begin, end);
            begin = s.find(' ', end) + 1;
            end = s.find(' ', begin) - 1;
        }
        begin = s.rfind(' ') + 1, end = s.size() - 1;

        reverse(s, begin, end);

        return s;
    }
};

int main()
{
    std::string s1("abcd efgh klm");
    Solution ss;
    std::string s2 = ss.reverseWords(s1);
    std::cout << s2 << std::endl;

	return 0;
}